package org.ouwa.lms.client.ui.login;

import org.ouwa.lms.client.manager.ManagerRegistry;
import org.ouwa.lms.client.model.LoginInfo;
import org.ouwa.lms.client.support.async.MyAsyncCallback;
import org.ouwa.lms.client.ui.EventPane;
import org.ouwa.lms.client.ui.event.LoginEvent;
import org.ouwa.lms.client.ui.util.WidgetUtil;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class LoginPane extends EventPane {
	private static final String OUWA_IMG_URL = "images/ouwa-logo.jpg";
	private static final String GOOGLE_IMG_URL = "images/googleAccounts.gif";
	
	private Anchor loginLink;
	
	public LoginPane(ManagerRegistry managerRegistry) {
		super(managerRegistry);
		handleGoogleSignin();
		
		VerticalPanel mainPanel = new VerticalPanel();
		mainPanel.setStyleName("wrapper");
		mainPanel.setSpacing(10);
		
		Image logoImage = new Image(OUWA_IMG_URL);
		mainPanel.add(WidgetUtil.addVerticalGap("5px"));
		mainPanel.add(logoImage);
		mainPanel.add(WidgetUtil.addVerticalGap("20px"));
		mainPanel.setCellHorizontalAlignment(logoImage, VerticalPanel.ALIGN_CENTER);
		
		HorizontalPanel messagePanel = new HorizontalPanel();
		messagePanel.setSpacing(5);
		Image googleImage = new Image(GOOGLE_IMG_URL);
		messagePanel.add(googleImage);
		messagePanel.add(WidgetUtil.addHorizontalGap("10px"));
		
		loginLink = new Anchor("Log in");
		messagePanel.add(loginLink);
		Label loginMessage = new Label("securely with your Google account to access the app.");
		messagePanel.add(loginMessage);
		messagePanel.setCellVerticalAlignment(loginLink, HorizontalPanel.ALIGN_MIDDLE);
		messagePanel.setCellVerticalAlignment(loginMessage, HorizontalPanel.ALIGN_MIDDLE);
		
		mainPanel.add(messagePanel);
		mainPanel.setCellHorizontalAlignment(messagePanel, VerticalPanel.ALIGN_CENTER);
		
		initWidget(mainPanel);
	}
	
	private void handleGoogleSignin() {
		final LoginEvent loginEvent = new LoginEvent(this);
		getManagerRegistry().getRemoteServiceManager().getGoogleLoginService().login(GWT.getHostPageBaseURL(),
				new MyAsyncCallback<LoginInfo>() {
			@Override
			public void onSuccess(LoginInfo result) {
				loginLink.setHref(result.getLoginUrl());
				String email = result.getEmailAddress();
				String nickname = result.getNickname();
				String loginUrl = result.getLoginUrl();
				
				loginEvent.setUsername(email);
				loginEvent.setNickname(nickname);
				loginEvent.setLoginUrl(loginUrl);
				if(result.isLoggedIn()) {
					loginEvent.setCredentials(true);
				}
				
				fireEvent(loginEvent);
			}
		});
	}
}
